package cn.codeguy.component_download;

import com.facebook.stetho.okhttp3.StethoInterceptor;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import cn.dankal.basiclib.domain.HttpLoggingInterceptor;
import cn.dankal.basiclib.domain.TokenInterceptor;
import me.jessyan.progressmanager.ProgressManager;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

/**
 * Created by fred
 * Date: 2018/9/14.
 * Time: 10:11
 * classDescription:
 */
public class DownloadApi {

    private DownloadService downloadService;

    private DownloadApi() {
        OkHttpClient okHttp = getOkhttpInstance();

        downloadService = new Retrofit.Builder()
                .baseUrl("https://img.cheersto.cn/")
                .client(okHttp)
                .addConverterFactory(FastJsonConverterFactory.create())
                .callbackExecutor(Executors.newFixedThreadPool(1))
                .build()
                .create(DownloadService.class);
    }

    private static class SingletonHolder {
        private static final DownloadApi INSTANCE = new DownloadApi();
    }


    public static OkHttpClient getOkhttpInstance() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient
                okHttpClient = ProgressManager.getInstance().with(new OkHttpClient.Builder())
                .readTimeout(7000, TimeUnit.MILLISECONDS)
                .connectTimeout(7000, TimeUnit.MILLISECONDS)
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new TokenInterceptor())
                .addNetworkInterceptor(new StethoInterceptor())
                .hostnameVerifier(new HostnameVerifier() {
                    /**
                     * Verify that the host name is an acceptable match with
                     * the server's authentication scheme.
                     *
                     * @param hostname the host name
                     * @param session  SSLSession used on the connection to host
                     * @return true if the host name is acceptable
                     */
                    //忽略证书
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .build();
        return okHttpClient;
    }


    /**
     * 获取单例
     *
     * @return 该类对象
     */
    public static DownloadApi getInstance() {
        return SingletonHolder.INSTANCE;
    }


    public Call<ResponseBody> download(String url) {
        return downloadService.download(url);
    }

}
